package com.ht.pms.core.util;

import java.beans.PropertyDescriptor;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.ht.pms.core.common.constant.SalaryConstants;
import com.ht.pms.core.dto.poi.ExcelBean;
import com.ht.pms.core.handler.ExcelExportHandler;

public class PoiUtils {
	private final static String excel2003L = ".xls"; // 2003- 版本的excel
	private final static String excel2007U = ".xlsx"; // 2007+ 版本的excel
	
	private final static int EXPROT_PAGESIZE = 1000;

	/************************************* 文件上传 ****************************/
	public static List<List<Object>> getBankListByExcel(InputStream in, String fileName) throws Exception {
		List<List<Object>> list = null;

		// 创建Excel工作薄
		Workbook work = getWorkbook(in, fileName);
		if (null == work) {
			throw new Exception("创建Excel工作薄为空！");
		}
		Sheet sheet = null;
		Row row = null;
		Cell cell = null;

		list = new ArrayList<List<Object>>();
		// 遍历Excel中所有的sheet
		for (int i = 0; i < work.getNumberOfSheets(); i++) {
			sheet = work.getSheetAt(i);
			if (sheet == null) {
				continue;
			}

			// 遍历当前sheet中的所有行
			for (int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum(); j++) {
				row = sheet.getRow(j);
				if (row == null) {
					continue;
				}

				// 遍历所有的列
				List<Object> li = new ArrayList<Object>();
				for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
					cell = row.getCell(y);
					li.add(getCellValue(cell));
				}
				list.add(li);
			}
		}
		// work.close();
		return list;
	}

	/**
	 * 描述：根据文件后缀，自适应上传文件的版本
	 * 
	 * @param inStr,fileName
	 * @return
	 * @throws Exception
	 */
	public static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
		Workbook wb = null;
		String fileType = fileName.substring(fileName.lastIndexOf("."));
		if (excel2003L.equals(fileType)) {
			wb = new HSSFWorkbook(inStr); // 2003-
		} else if (excel2007U.equals(fileType)) {
			wb = new XSSFWorkbook(inStr); // 2007+
		} else {
			throw new Exception("解析的文件格式有误！");
		}
		return wb;
	}

	/**
	 * 描述：对表格中数值进行格式化
	 * 
	 * @param cell
	 * @return
	 */
	public static Object getCellValue(Cell cell) {
		Object value = null;
		DecimalFormat df = new DecimalFormat("0"); // 格式化number String字符
		SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); // 日期格式化
		DecimalFormat df2 = new DecimalFormat("0.00"); // 格式化数字

		switch (cell.getCellType()) {
		case Cell.CELL_TYPE_STRING:
			value = cell.getRichStringCellValue().getString();
			break;
		case Cell.CELL_TYPE_NUMERIC:
			if ("General".equals(cell.getCellStyle().getDataFormatString())) {
				value = df.format(cell.getNumericCellValue());
				// } else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
			} else if (HSSFDateUtil.isCellDateFormatted(cell)) { // 判断日期类型
				value = sdf.format(cell.getDateCellValue());
			} else {
				value = df2.format(cell.getNumericCellValue());
			}
			break;
		case Cell.CELL_TYPE_BOOLEAN:
			value = cell.getBooleanCellValue();
			break;
		case Cell.CELL_TYPE_BLANK:
			break;
		default:
			break;
		}
		return value;
	}

	/**
	 * 分批次导出
	 * 
	 * @param sheetName
	 *            工作簿名称
	 * @param clazz
	 *            数据源model类型
	 * @param objs
	 *            excel标题列以及对应model字段名
	 * @param map
	 *            标题列行数以及cell字体样式
	 * @return
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws ClassNotFoundException
	 * @throws IntrospectionException
	 * @throws ParseException
	 */
	private static CellStyle fontStyle;
	private static CellStyle fontStyleInt;
	private static CellStyle fontStyleDouble;
	private static CellStyle fontStyleString;
	private static CellStyle fontStyleDate;

	public static SXSSFWorkbook createExcelFile(List<ExcelBean> excelBeans, ExcelExportHandler handler)
			throws Exception {
		// 创建新的Excel 工作簿
		SXSSFWorkbook workbook = new SXSSFWorkbook(1000);
		// 在Excel工作簿中建一工作表，其名为缺省值, 也可以指定Sheet名称
		Sheet sheet = workbook.createSheet();
		// 以下为excel的字体样式以及excel的标题与内容的创建，下面会具体分析;
		// createFont(workbook);// 字体样式
		for (int i = 0; i < excelBeans.size(); i++) {
			sheet.autoSizeColumn((short) i);
		}
		sheet.createFreezePane(5, 1);;
		fontStyle = PoiStyleUtils.getStyle(workbook);
		fontStyleInt = PoiStyleUtils.getColumnNumCentStyle(workbook, SalaryConstants.INT_TYPE);
		fontStyleDouble = PoiStyleUtils.getColumnNumCentStyle(workbook, SalaryConstants.DOUBLE_TYPE);
		fontStyleString = PoiStyleUtils.getColumnNumCentStyle(workbook, SalaryConstants.STRING_TYPE);
		fontStyleDate = PoiStyleUtils.getColumnNumCentStyle(workbook, SalaryConstants.DATE_TYPE);
		createTableHeader(sheet, excelBeans);// 创建标题（头）
		createTableRows(sheet, excelBeans, handler);// 创建内容

		return workbook;
	}

	/**
	 * 导出excel模板
	 * 
	 * @param excelBeans
	 * @return
	 * @throws Exception
	 */
	public static SXSSFWorkbook createExcelTemplate(List<ExcelBean> excelBeans) throws Exception {
		// 创建新的Excel 工作簿
		SXSSFWorkbook workbook = new SXSSFWorkbook(1000);
		// 在Excel工作簿中建一工作表，其名为缺省值, 也可以指定Sheet名称
		Sheet sheet = workbook.createSheet();
		// 以下为excel的字体样式以及excel的标题与内容的创建，下面会具体分析;
		// createFont(workbook);// 字体样式
		for (int i = 0; i < excelBeans.size(); i++) {
			sheet.autoSizeColumn((short) i);
		}
		fontStyle = PoiStyleUtils.getStyle(workbook);
		createTableHeader(sheet, excelBeans);// 创建标题（头）
		return workbook;
	}

	/**
	 * 一次导出
	 * 
	 * @param excelBeans
	 * @param objs
	 * @param clazz
	 * @param sheetName
	 * @return
	 * @throws Exception
	 */
	public static SXSSFWorkbook createExcelFile(List<ExcelBean> excelBeans, List objs, Class clazz, String sheetName)
			throws Exception {
		// 创建新的Excel 工作簿
		SXSSFWorkbook workbook = new SXSSFWorkbook(1000);
		Sheet sheet = workbook.createSheet(sheetName);

		// 字体样式
		for (int i = 0; i < excelBeans.size(); i++) {
			sheet.autoSizeColumn((short) i);
		}
		fontStyle = PoiStyleUtils.getStyle(workbook);
		fontStyleInt = PoiStyleUtils.getColumnNumCentStyle(workbook, SalaryConstants.INT_TYPE);
		fontStyleDouble = PoiStyleUtils.getColumnNumCentStyle(workbook, SalaryConstants.DOUBLE_TYPE);
		fontStyleString = PoiStyleUtils.getColumnNumCentStyle(workbook, SalaryConstants.STRING_TYPE);
		fontStyleDate = PoiStyleUtils.getColumnNumCentStyle(workbook, SalaryConstants.DATE_TYPE);
		createTableHeader(sheet, excelBeans);// 创建标题（头）
		if (objs != null && !objs.isEmpty()) {
			createTableRows(sheet, excelBeans, objs, clazz);// 创建内容
		}
		return workbook;
	}

	/**
	 * 根据ExcelMapping 生成列头
	 * 
	 * @param sheet
	 *            工作簿
	 * @param map
	 *            每行每个单元格对应的列头信息
	 */
	public static final void createTableHeader(Sheet sheet, List<ExcelBean> excels) {
		int startIndex = 0;// cell起始位置
		int endIndex = 0;// cell终止位置

		Row row = sheet.createRow(0);
		row.setHeight((short) (200 * 2.7));
		for (int x = 0; x < excels.size(); x++) {
			// 合并单元格
			if (excels.get(x).getCols() > 1) {
				if (x == 0) {
					endIndex += excels.get(x).getCols() - 1;
					CellRangeAddress range = new CellRangeAddress(0, 0, startIndex, endIndex);
					sheet.addMergedRegion(range);
					startIndex += excels.get(x).getCols();
				} else {
					endIndex += excels.get(x).getCols();
					CellRangeAddress range = new CellRangeAddress(0, 0, startIndex, endIndex);
					sheet.addMergedRegion(range);
					startIndex += excels.get(x).getCols();
				}
				Cell cell = row.createCell(startIndex - excels.get(x).getCols());
				cell.setCellValue(excels.get(x).getHeadTextName());// 设置内容
				if (excels.get(x).getCellStyle() != null) {
					cell.setCellStyle(excels.get(x).getCellStyle());// 设置格式
				}
				cell.setCellStyle(fontStyle);
			} else {

				Cell cell = row.createCell(x);
				cell.setCellValue(excels.get(x).getHeadTextName());// 设置内容
				if (excels.get(x).getCellStyle() != null) {
					cell.setCellStyle(excels.get(x).getCellStyle());// 设置格式
				}
				cell.setCellStyle(fontStyle);
			}

		}
	}

	/**
	 * 一次导出
	 * 
	 * @param sheet
	 * @param map
	 * @param objs
	 * @param clazz
	 */
	@SuppressWarnings("rawtypes")
	public static void createTableRows(Sheet sheet, List<ExcelBean> ems, List objs, Class clazz) throws Exception {
		int rowindex = 1;
		List<Integer> widths = new ArrayList<Integer>(ems.size());
		for (Object obj : objs) {
			Row row = sheet.createRow(rowindex);
			for (int i = 0; i < ems.size(); i++) {
				ExcelBean em = (ExcelBean) ems.get(i);
				// 获得get方法
				PropertyDescriptor pd = new PropertyDescriptor(em.getPropertyName(), clazz);
				Method getMethod = pd.getReadMethod();
				Object rtn = getMethod.invoke(obj);
				String value = "";
				// 如果是日期类型 进行 转换
				if (rtn != null) {
					if (rtn instanceof Date) {
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
						value = sdf.format((Date) rtn);
					} else if (rtn instanceof BigDecimal) {
						NumberFormat nf = new DecimalFormat("#,##0.00");
						value = nf.format((BigDecimal) rtn).toString();
					} else if ((rtn instanceof Integer) && (Integer.valueOf(rtn.toString()) < 0)) {
						value = "--";
					} else {
						value = rtn.toString();
					}
				}
				// 以上是对应表头与内容设置

				Cell cell = row.createCell(i);
				cell.setCellValue(value);
				cell.setCellType(XSSFCell.CELL_TYPE_STRING);
				cell.setCellStyle(fontStyle);
				// 获得最大列宽
				int width = value.getBytes().length * 300;
				// 还未设置，设置当前
				if (widths.size() <= i) {
					widths.add(width);
					continue;
				}
				// 比原来大，更新数据
				if (width > widths.get(i)) {
					widths.set(i, width);
				}
			}
			rowindex++;
		}
		// 设置列宽
		for (int index = 0; index < widths.size(); index++) {
			Integer width = widths.get(index);
			width = width < 2500 ? 2500 : width + 300;
			width = width > 10000 ? 10000 + 300 : width + 300;
			sheet.setColumnWidth(index, width);
		}
	}

	/**
	 * 多批次导出
	 * 
	 * @param sheet
	 * @param map
	 * @param objs
	 * @param clazz
	 */
	public static void createTableRows(Sheet sheet, List<ExcelBean> ems, ExcelExportHandler handler) throws Exception {
		int rowindex = 1;
		int totalCount = handler.getExcelDataCount();
		
		int totalPage = (totalCount + EXPROT_PAGESIZE - 1) / EXPROT_PAGESIZE;
		
		 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		for (int currentPage = 1; currentPage <= totalPage; currentPage++) {
			List<Map<String, Object>> objs = handler.getExcelDataByPage(currentPage, EXPROT_PAGESIZE);
			
			for (Map<String, Object> obj : objs) {
				Row row = sheet.createRow(rowindex);
				row.setHeight((short) (200 * 1.8));
				for (int y = 0; y < ems.size(); y++) {
					ExcelBean em = ems.get(y);
					String value = obj.get(em.getPropertyName()) + "";
					Cell cell = row.createCell(y);
					
					ValueSelector.setValue(value, cell);
					
					
					switch (em.getType()) {
					case SalaryConstants.INT_TYPE:
						try {
							Integer valueOf = Integer.valueOf(value);
							cell.setCellType(Cell.CELL_TYPE_NUMERIC);
							cell.setCellStyle(fontStyleInt);
							cell.setCellValue(valueOf);
						} catch (Exception e) {
							cell.setCellType(Cell.CELL_TYPE_STRING);
							cell.setCellStyle(fontStyleString);
							cell.setCellValue(value);
						}
						break;
					case SalaryConstants.DOUBLE_TYPE:
						try {
							Double valueOf = Double.valueOf(value);
							cell.setCellType(Cell.CELL_TYPE_NUMERIC);
							cell.setCellStyle(fontStyleDouble);
							cell.setCellValue(valueOf);
						} catch (Exception e) {
							cell.setCellType(Cell.CELL_TYPE_STRING);
							cell.setCellStyle(fontStyleString);
							cell.setCellValue(value);
						}
						break;
					case SalaryConstants.DATE_TYPE:
						try {
							Date date =dateFormat.parse(value);
							cell.setCellType(Cell.CELL_TYPE_STRING);
							cell.setCellStyle(fontStyleDate);
							cell.setCellValue(date);
						} catch (Exception e) {
							cell.setCellType(Cell.CELL_TYPE_STRING);
							cell.setCellStyle(fontStyleString);
							cell.setCellValue(value);
						}
						break;
					case SalaryConstants.STRING_TYPE:
						cell.setCellType(Cell.CELL_TYPE_STRING);
						cell.setCellStyle(fontStyleString);
						cell.setCellValue(value);
						break;
					default:
						break;
					}
					// 获得最大列宽
				}
				rowindex++;
			}
		}
	}
	
	public static void main(String[] args) {
		Date javaDate = HSSFDateUtil.getJavaDate(43207);
		System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(javaDate));
		
	}
}
